'''
Author: your name
Date: 2021-11-29 17:24:28
LastEditTime: 2021-12-01 16:54:17
LastEditors: Please set LastEditors
Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
FilePath: \flood-evacuation-risk-assessment\IO.py
'''
import pandas as pd
import shapefile
import os
import scipy.spatial as spt
import numpy as np
from shapely.geometry import Point
from shapely.geometry import LineString
#读取特征点，输出Gmsh geo 脚本文件
def read_character_point_hydrodynamic_data(filename):
    if os.path.exists(filename):
        name, filetype = os.path.splitext(filename)
        if filetype == ".csv":
            data = pd.read_csv(filename)
        elif filetype == ".txt":
            data = pd.read_table(filename, sep = ",", index_col=[0])
    else:
        print("Error in read character point data!!!!!!!!!!")
    return data

#https://stackoverflow.com/questions/55112771/read-shapefiles-into-dataframe/55555857
def convertShpToPandas(sf):
    fields = [x[0] for x in sf.fields][1:]
    records = sf.records()
    shps = [s.points for s in sf.shapes()]
    sf_df = pd.DataFrame(columns = fields, data = records)
    return sf_df



def findStartEndPoint(pData, lData):
    tplist = []
    for i in range(0, pData.shape[0]):
        tplist.append([pData.loc[i,"x"], pData.loc[i,"y"]])
    tplist = np.array(tplist)
    tkt = spt.KDTree(data = tplist, leafsize = 10)
    ctkt = spt.cKDTree(tplist)

    linesp = []
    lineep = []
    if 'localSp' not in lData.columns:
        for i in range(0, lData.shape[0]):
            sssp = Point([lData.loc[i, "xin"],lData.loc[i, "yin"]])
            edp = Point([lData.loc[i, "xout"],lData.loc[i, "yout"]])
            dist, NearstPoint = tkt.query(sssp)
            if(dist < 1):
                linesp.append(NearstPoint)
            else:
                print("error in finding line start")

            dist, NearstPoint = tkt.query(edp)
            if(dist < 1):
                lineep.append(NearstPoint)
            else:
                print(dist)
                print("error in finding tunnel line start")
    lData["localSp"] = linesp
    lData['localEp'] = lineep
    return lData